package com.uaf.vxalipaybill.provider.service.read.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.uaf.api.vo.req.BaseReqVo;
import com.uaf.common.dataextract.DataextractUtils;
import com.uaf.common.date.utils.DateUtils;
import com.uaf.log.MySlf4j;
import com.uaf.vxalipaybill.api.exception.VxAlipayBillException;
import com.uaf.vxalipaybill.api.exception.VxAlipayBillServiceException;
import com.uaf.vxalipaybill.api.vo.req.VxAlipayBillDataExtractReqVo;
import com.uaf.vxalipaybill.api.vo.req.VxAlipayBillQueryReqVo;
import com.uaf.vxalipaybill.api.vo.resp.VxAlipayBillDataInputsRespVo;
import com.uaf.vxalipaybill.api.vo.resp.VxAlipayBillQueryRespVo;
import com.uaf.vxalipaybill.api.vo.resp.VxAlipayBillReqBeanListRespVo;
import com.uaf.vxalipaybill.api.vo.resp.VxAlipayBillReqBeanVo;
import com.uaf.vxalipaybill.provider.bean.VxAlipayAnalysisDetailBean;
import com.uaf.vxalipaybill.provider.bean.VxAlipayAnalysisRespBean;
import com.uaf.vxalipaybill.provider.bean.VxAlipayBillAnalysisIntergrated;
import com.uaf.vxalipaybill.provider.bean.VxAlipayBillAnalysisReqBean;
import com.uaf.vxalipaybill.provider.bean.VxAlipayBillAnalysisReqExtractBean;
import com.uaf.vxalipaybill.provider.bean.VxAlipayBillArchiveInfoBean;
import com.uaf.vxalipaybill.provider.bean.VxAlipayMerchantConfigBean;
import com.uaf.vxalipaybill.provider.dao.VxAlipayAnalysisDetailBeanDao;
import com.uaf.vxalipaybill.provider.dao.VxAlipayAnalysisRespBeanDao;
import com.uaf.vxalipaybill.provider.dao.VxAlipayBillAnalysisReqBeanDao;
import com.uaf.vxalipaybill.provider.dao.VxAlipayBillArchiveInfoBeanDao;
import com.uaf.vxalipaybill.provider.dao.VxAlipayMerchantConfigBeanDao;
import com.uaf.vxalipaybill.provider.service.read.IVxAlipayBillReadService;
import com.uaf.vxalipaybill.provider.service.write.IVxAlipayBillWriteService;
import com.uaf.vxalipaybill.provider.utils.VxAlipayBillConstantUtils;
import com.uaf.vxalipaybill.provider.utils.VxAlipayDataExtractEnum;

/**
 * @filename VxAlipayBillWriteServiceImpl.java
 * @description 微信支付宝账单服务类
 * @author 马庆智
 * @date 2021/9/15 11:06
 */
@Service
public class VxAlipayBillReadServiceImpl implements IVxAlipayBillReadService {

	@Autowired
	private VxAlipayBillAnalysisReqBeanDao vxAlipayBillAnalysisReqBeanDao;

	@Autowired
	private VxAlipayMerchantConfigBeanDao vxAlipayMerchantConfigBeanDao;

	@Autowired
	private VxAlipayAnalysisDetailBeanDao vxAlipayAnalysisDetailBeanDao;

	@Autowired
	private VxAlipayAnalysisRespBeanDao vxAlipayAnalysisRespBeanDao;

	@Autowired
	private VxAlipayBillArchiveInfoBeanDao vxAlipayBillArchiveInfoBeanDao;

	@Autowired
	private IVxAlipayBillWriteService vxAlipayBillWriteService;

	/**
	 * 功能描述  微信支付宝账单授权结果返回值查询
	 * @param  req  微信支付宝参数
	 * @return vxAlipayBillQueryRespVo 微信支付宝查询响应类
	 * @author 马庆智
	 * @date 2021/9/14 10:36
	 */
	@Override
	public VxAlipayBillQueryRespVo queryVxAlipayAuthResult(BaseReqVo<VxAlipayBillQueryReqVo> req) {

		VxAlipayBillAnalysisReqBean vxalipayBean = new VxAlipayBillAnalysisReqBean();
		vxalipayBean.setSource(VxAlipayBillConstantUtils.VX_ALIPAY_SOURCE_VX);
		vxalipayBean.setCertNo(req.getData().getCertNo());
		vxalipayBean.setMerchantId(req.getMerchantId());

		// 获取商户信息
		VxAlipayMerchantConfigBean merchantConfigBean = vxAlipayMerchantConfigBeanDao
				.queryVxAlipayMerchantInfo(req.getMerchantId());
		vxalipayBean.setCacheDays(merchantConfigBean.getCacheDays());
		// 获取微信授权信息
		VxAlipayBillAnalysisReqBean vxBean = vxAlipayBillAnalysisReqBeanDao
				.queryVxAlipayBillAnalysisReqBean(vxalipayBean);
		String vxAuthStatus = VxAlipayBillConstantUtils.STATUS_BEGIN;
		VxAlipayBillQueryRespVo vxAlipayBillQueryRespVo = new VxAlipayBillQueryRespVo();
		if (null != vxBean) {
			// 查询历史记录，插入对应缓存信息
			if (VxAlipayBillConstantUtils.STATUS_LOCAL.equals(vxBean.getStatus())
					|| VxAlipayBillConstantUtils.STATUS_SUCCESS.equals(vxBean.getStatus())) {
				boolean cacheFlag=vxAlipayBillWriteService
						.isCache(req.getData().getBusinessId(), vxBean, merchantConfigBean.getCacheDays());
				if (cacheFlag) {
					vxAuthStatus = VxAlipayBillConstantUtils.STATUS_SUCCESS;
				}
			}
		}

		// 获取支付宝授权信息
		vxalipayBean.setSource(VxAlipayBillConstantUtils.VX_ALIPAY_SOURCE_ALIPAY);
		VxAlipayBillAnalysisReqBean alipayBean = vxAlipayBillAnalysisReqBeanDao
				.queryVxAlipayBillAnalysisReqBean(vxalipayBean);
		String alipayAuthStatus = VxAlipayBillConstantUtils.STATUS_BEGIN;
		if (null != alipayBean) {
			// 查询历史记录，插入对应缓存信息
			if (VxAlipayBillConstantUtils.STATUS_LOCAL.equals(alipayBean.getStatus())
					|| VxAlipayBillConstantUtils.STATUS_SUCCESS.equals(alipayBean.getStatus())) {
				boolean cacheFlag=vxAlipayBillWriteService
						.isCache(req.getData().getBusinessId(), alipayBean, merchantConfigBean.getCacheDays());
				if (cacheFlag) {
					alipayAuthStatus = VxAlipayBillConstantUtils.STATUS_SUCCESS;
				}
			}
		}

		vxAlipayBillQueryRespVo.setVxAuthStatus(vxAuthStatus);
		vxAlipayBillQueryRespVo.setAlipayAuthStatus(alipayAuthStatus);
		return vxAlipayBillQueryRespVo;
	}

	/**
	 * 功能描述 壹融站SAS数据提取-微信支付宝账单数据接口
	 * @param baseReqVo 请求报文
	 * @return com.uaf.vxalipaybill.api.vo.resp.VxAlipayBillDataInputsRespVo
	 * @author 马庆智
	 * @date 2021/10/8 11:08
	 */
	@Override
	public VxAlipayBillDataInputsRespVo dataextractVxAlipayBillData(BaseReqVo<VxAlipayBillDataExtractReqVo> baseReqVo) {
		VxAlipayBillDataExtractReqVo dataBaseReqVo = baseReqVo.getData();
		/** 业务编号 */
		String businessId = dataBaseReqVo.getBusinessId();
		/** 身份证号码*/
		String queryCertNum = dataBaseReqVo.getQueryCertNum();
		/** 响应信息*/
		VxAlipayBillDataInputsRespVo vxAlipayBillDataInputsRespVo = new VxAlipayBillDataInputsRespVo();
		vxAlipayBillDataInputsRespVo.setApplyNo(businessId);
		vxAlipayBillDataInputsRespVo.setStreamNo(dataBaseReqVo.getStreamNo());
		vxAlipayBillDataInputsRespVo.setProductNo(dataBaseReqVo.getProductNo());
		/**通过 业务编码,身份证号码查询最新的 微信支付宝账单解析信息*/
		VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBeanSearch = new VxAlipayBillAnalysisReqBean();
		vxAlipayBillAnalysisReqBeanSearch.setBussinessId(baseReqVo.getData().getBusinessId());
		vxAlipayBillAnalysisReqBeanSearch.setMerchantId(baseReqVo.getMerchantId());
		vxAlipayBillAnalysisReqBeanSearch.setCertNo(baseReqVo.getData().getQueryCertNum());
		try {
			/**微信支付宝账单解析请求数据*/
			List<Map<String, Object>> vxAlipayBillAnalysisReqBeanDataMapList = new ArrayList<>();

			vxAlipayBillAnalysisReqBeanSearch.setSource(VxAlipayBillConstantUtils.VX_ALIPAY_SOURCE_VX);
			Map<String, Object> vxMap = vxAlipayBillAnalysisReqBeanDao
					.queryVxAlipayBillAnalysisReqBeanData(vxAlipayBillAnalysisReqBeanSearch);
			if (vxMap != null) {
				vxAlipayBillAnalysisReqBeanDataMapList.add(vxMap);
			}
			vxAlipayBillAnalysisReqBeanSearch.setSource(VxAlipayBillConstantUtils.VX_ALIPAY_SOURCE_ALIPAY);
			Map<String, Object> alipayMap = vxAlipayBillAnalysisReqBeanDao
					.queryVxAlipayBillAnalysisReqBeanData(vxAlipayBillAnalysisReqBeanSearch);
			if (alipayMap != null) {
				vxAlipayBillAnalysisReqBeanDataMapList.add(alipayMap);
			}
			if (null == vxAlipayBillAnalysisReqBeanDataMapList || vxAlipayBillAnalysisReqBeanDataMapList.size() == 0) {
				throw new VxAlipayBillServiceException(VxAlipayBillException.ERR_SAS001);
			}
			List<Map<String, List<Object>>> vxAlipayBillAnalysisReqBeanDataResultList = DataextractUtils
					.transformData(vxAlipayBillAnalysisReqBeanDataMapList, VxAlipayBillAnalysisReqExtractBean.class);
			vxAlipayBillDataInputsRespVo.setVxAlipayBillAnalysisReq(vxAlipayBillAnalysisReqBeanDataResultList);

			/**微信支付宝归档*/
			List<Map<String, Object>> vxAlipayBillArchiveInfoBeanMapList = new ArrayList<>();
			VxAlipayBillArchiveInfoBean vxAlipayBillArchiveInfoBean = new VxAlipayBillArchiveInfoBean();
			vxAlipayBillArchiveInfoBean.setCertNo(queryCertNum);
			vxAlipayBillArchiveInfoBean.setSource(VxAlipayBillConstantUtils.VX_ALIPAY_SOURCE_VX);

			Map<String, Object> vxBillArchiveInfoBeanMapList = vxAlipayBillArchiveInfoBeanDao
					.queryVxAlipayBillArchiveInfoBeanData(vxAlipayBillArchiveInfoBean);
			if (vxBillArchiveInfoBeanMapList != null) {
				vxAlipayBillArchiveInfoBeanMapList.add(vxBillArchiveInfoBeanMapList);
			}

			vxAlipayBillArchiveInfoBean.setSource(VxAlipayBillConstantUtils.VX_ALIPAY_SOURCE_ALIPAY);
			Map<String, Object> alipayBillArchiveInfoBeanMapList = vxAlipayBillArchiveInfoBeanDao
					.queryVxAlipayBillArchiveInfoBeanData(vxAlipayBillArchiveInfoBean);
			if (alipayBillArchiveInfoBeanMapList != null) {
				vxAlipayBillArchiveInfoBeanMapList.add(alipayBillArchiveInfoBeanMapList);
			}

			List<Map<String, List<Object>>> vxAlipayBillArchiveInfoBeanDataResultList = DataextractUtils
					.transformData(vxAlipayBillArchiveInfoBeanMapList, VxAlipayBillArchiveInfoBean.class);
			vxAlipayBillDataInputsRespVo.setVxAlipayBillArchiveInfo(vxAlipayBillArchiveInfoBeanDataResultList);

			/**微信支付宝账单解析响应*/
			List<Map<String, Object>> vxAlipayAnalysisRespBeanMapList = new ArrayList<>();
			for (int i = 0; i < vxAlipayBillAnalysisReqBeanDataMapList.size(); i++) {
				String billAnalysisReqId = vxAlipayBillAnalysisReqBeanDataMapList.get(i).get("BILL_ANALYSIS_REQ_ID")
						.toString();
				Map<String, Object> vxAlipayAnalysisRespBeanMap = vxAlipayAnalysisRespBeanDao
						.queryVxAlipayAnalysisRespBeanData(billAnalysisReqId);
				if (vxAlipayAnalysisRespBeanMap != null && vxAlipayAnalysisRespBeanMap.size() > 0) {
					vxAlipayAnalysisRespBeanMapList.add(vxAlipayAnalysisRespBeanMap);
				}
			}
			List<Map<String, List<Object>>> vxAlipayAnalysisRespBeanResultList = DataextractUtils
					.transformData(vxAlipayAnalysisRespBeanMapList, VxAlipayAnalysisRespBean.class);
			vxAlipayBillDataInputsRespVo.setVxAlipayAnalysisResp(vxAlipayAnalysisRespBeanResultList);

			/**微信支付宝账单解析数据整合表*/
			List<Map<String, Object>> vxAlipayBillAnalysisIntergratedMapList = new ArrayList<>();
			for (int i = 0; i < vxAlipayBillAnalysisReqBeanDataMapList.size(); i++) {
				String billAnalysisReqId = vxAlipayBillAnalysisReqBeanDataMapList.get(i).get("BILL_ANALYSIS_REQ_ID")
						.toString();
				if ("VX".equals(vxAlipayBillAnalysisReqBeanDataMapList.get(i).get("SOURCE"))) {
					/**微信数据整合*/
					List<Map<String, Object>> vxBillAnalysisIntergratedMapList = vxBillAnalysisIntergrated(
							billAnalysisReqId);

					for (int a = 0; a < vxBillAnalysisIntergratedMapList.size(); a++) {
						Map<String, Object> map = vxBillAnalysisIntergratedMapList.get(a);
						vxAlipayBillAnalysisIntergratedMapList.add(map);
					}
				} else {
					List<Map<String, Object>> alipayBillAnalysisIntergratedMapList = alipayBillAnalysisIntergrated(
							billAnalysisReqId);

					for (int b = 0; b < alipayBillAnalysisIntergratedMapList.size(); b++) {
						Map<String, Object> map = alipayBillAnalysisIntergratedMapList.get(b);
						vxAlipayBillAnalysisIntergratedMapList.add(map);
					}
				}
			}

			DataextractUtils
					.transformPageData(vxAlipayBillAnalysisIntergratedMapList, VxAlipayBillAnalysisIntergrated.class,
							vxAlipayBillDataInputsRespVo,
							VxAlipayDataExtractEnum.UAF_CRT_VX_ALIPAY_BILL_INTERGRATED.getFieldName(),
							VxAlipayDataExtractEnum.UAF_CRT_VX_ALIPAY_BILL_INTERGRATED.getTableSum());

		} catch (Exception e) {
			MySlf4j.textError("壹融站SAS数据提取微信支付宝账单数据接口,业务编号:{0},身份证号 certNo:{1},异常:{2}", businessId, queryCertNum,
					MySlf4j.ExceptionToString(e));
			throw new VxAlipayBillServiceException(VxAlipayBillException.ERR_100000);
		}

		return vxAlipayBillDataInputsRespVo;
	}

	/**
	 * 功能描述 微信数据整合
	 * @param  billAnalysisReqId  请求id
	 * @return
	 * @author 马庆智
	 * @date 2022/3/31 10:02
	 */
	private List<Map<String, Object>> vxBillAnalysisIntergrated(String billAnalysisReqId) {
		List<Map<String, Object>> vxBillAnalysisIntergratedMapList = new ArrayList<>();

		VxAlipayAnalysisDetailBean vxAlipayAnalysisDetailBean = new VxAlipayAnalysisDetailBean();
		/**微信18个union拼接*/
		for (int i = 1; i <= 18; i++) {
			vxAlipayAnalysisDetailBean.setBillAnalysisReqId(billAnalysisReqId);
			vxAlipayAnalysisDetailBean.setTableNumber(i);
			MySlf4j.textInfo("billAnalysisReqId:{0},微信收集数据,第{1}次查询VxAlipayAnalysisDetailBean表", billAnalysisReqId, i);
			List<Map<String, Object>> vxBillAnalysisIntergratedSelectMapList = vxAlipayAnalysisDetailBeanDao
					.queryVxBillAnalysisIntergrated(vxAlipayAnalysisDetailBean);
			if (null != vxBillAnalysisIntergratedSelectMapList || vxBillAnalysisIntergratedSelectMapList.size() > 0) {
				for (int t = 0; t < vxBillAnalysisIntergratedSelectMapList.size(); t++) {
					vxBillAnalysisIntergratedMapList.add(vxBillAnalysisIntergratedSelectMapList.get(t));
				}
			}
		}

		List<Map<String, Object>> vxBillAnalysisIntergratedSortMapList = vxBillAnalysisIntergratedMapList.stream()
				.sorted((o1, o2) -> {
					Date d1 = DateUtils.strToDate(o1.get("TRANS_DATE") + "", "yyyy-MM");
					Date d2 = DateUtils.strToDate(o2.get("TRANS_DATE") + "", "yyyy-MM");
					return d1.compareTo(d2);
				}).collect(Collectors.toList());

		return vxBillAnalysisIntergratedSortMapList;
	}

	/**
	 * 功能描述 支付宝数据整合
	 * @param  billAnalysisReqId  请求id
	 * @return
	 * @author 马庆智
	 * @date 2022/3/31 10:02
	 */
	private List<Map<String, Object>> alipayBillAnalysisIntergrated(String billAnalysisReqId) {
		List<Map<String, Object>> alipayBillAnalysisIntergratedMapList = new ArrayList<>();

		VxAlipayAnalysisDetailBean alipayAlipayAnalysisDetailBean = new VxAlipayAnalysisDetailBean();
		/**支付宝17个union拼接*/
		for (int i = 1; i <= 17; i++) {
			alipayAlipayAnalysisDetailBean.setBillAnalysisReqId(billAnalysisReqId);
			alipayAlipayAnalysisDetailBean.setTableNumber(i);
			MySlf4j.textInfo("billAnalysisReqId:{0},支付宝收集数据,第{1}次查询VxAlipayAnalysisDetailBean表", billAnalysisReqId, i);
			List<Map<String, Object>> alipayBillAnalysisIntergratedSelectMapList = vxAlipayAnalysisDetailBeanDao
					.queryAlipayBillAnalysisIntergrated(alipayAlipayAnalysisDetailBean);
			if (null != alipayBillAnalysisIntergratedSelectMapList
					|| alipayBillAnalysisIntergratedSelectMapList.size() > 0) {
				for (int t = 0; t < alipayBillAnalysisIntergratedSelectMapList.size(); t++) {
					alipayBillAnalysisIntergratedMapList.add(alipayBillAnalysisIntergratedSelectMapList.get(t));
				}
			}
		}
		List<Map<String, Object>> alipayBillAnalysisIntergratedSortMapList = alipayBillAnalysisIntergratedMapList
				.stream().sorted((o1, o2) -> {
					if (Integer.parseInt(((String) o1.get("TRANS_DATE")).split("-")[0] + ((String) o1.get("TRANS_DATE"))
							.split("-")[1]) < Integer.parseInt(
							((String) o2.get("TRANS_DATE")).split("-")[0] + ((String) o2.get("TRANS_DATE"))
									.split("-")[1])) {
						return 1;
					} else if (Integer.parseInt(
							((String) o1.get("TRANS_DATE")).split("-")[0] + ((String) o1.get("TRANS_DATE"))
									.split("-")[1]) == Integer.parseInt(
							((String) o2.get("TRANS_DATE")).split("-")[0] + ((String) o2.get("TRANS_DATE"))
									.split("-")[1])) {
						return 0;
					} else {
						return -1;
					}
				}).collect(Collectors.toList());

		return alipayBillAnalysisIntergratedSortMapList;
	}

	/**
	 * 功能描述 根据身份证号查询微信支付宝账单FileId等值
	 * @param certNo 身份证号
	 * @return VxAlipayBillReqBeanListRespVo
	 * @author 马庆智
	 * @date 2021/10/13 16:21
	 */
	public VxAlipayBillReqBeanListRespVo queryVxAlipayReqBeanList(String certNo, String merchantId) {
		VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBean = new VxAlipayBillAnalysisReqBean();
		vxAlipayBillAnalysisReqBean.setCertNo(certNo);
		vxAlipayBillAnalysisReqBean.setMerchantId(merchantId);
		List<Map<String, Object>> vxAlipayBillAnalysisReqBeanList = new ArrayList<>();

		vxAlipayBillAnalysisReqBean.setSource(VxAlipayBillConstantUtils.VX_ALIPAY_SOURCE_VX);
		Map<String, Object> vxMap = vxAlipayBillAnalysisReqBeanDao
				.queryVxAlipayBillAnalysisReqBeanData(vxAlipayBillAnalysisReqBean);
		if (vxMap != null) {
			vxAlipayBillAnalysisReqBeanList.add(vxMap);
		}
		vxAlipayBillAnalysisReqBean.setSource(VxAlipayBillConstantUtils.VX_ALIPAY_SOURCE_ALIPAY);
		Map<String, Object> alipayMap = vxAlipayBillAnalysisReqBeanDao
				.queryVxAlipayBillAnalysisReqBeanData(vxAlipayBillAnalysisReqBean);
		if (alipayMap != null) {
			vxAlipayBillAnalysisReqBeanList.add(alipayMap);
		}
		if (null == vxAlipayBillAnalysisReqBeanList || vxAlipayBillAnalysisReqBeanList.size() == 0) {
			throw new VxAlipayBillServiceException(VxAlipayBillException.ERR_100002);
		}

		List<VxAlipayBillReqBeanVo> vxAlipayBillReqBeanVoList = new ArrayList<VxAlipayBillReqBeanVo>();
		for (int i = 0; i < vxAlipayBillAnalysisReqBeanList.size(); i++) {
			VxAlipayBillReqBeanVo vxAlipayBillReqBeanVo = new VxAlipayBillReqBeanVo();
			vxAlipayBillReqBeanVo.setCertNo(vxAlipayBillAnalysisReqBeanList.get(i).get("CERT_NO").toString());
			vxAlipayBillReqBeanVo.setSource(vxAlipayBillAnalysisReqBeanList.get(i).get("SOURCE").toString());
			vxAlipayBillReqBeanVo.setFileId(vxAlipayBillAnalysisReqBeanList.get(i).get("FILE_ID").toString());
			vxAlipayBillReqBeanVo.setFileName(vxAlipayBillAnalysisReqBeanList.get(i).get("FILE_NAME").toString());
			vxAlipayBillReqBeanVo.setFilePath(vxAlipayBillAnalysisReqBeanList.get(i).get("FILE_PATH").toString());
			vxAlipayBillReqBeanVoList.add(vxAlipayBillReqBeanVo);
		}
		VxAlipayBillReqBeanListRespVo vxAlipayReqBeanListRespVo = new VxAlipayBillReqBeanListRespVo();
		vxAlipayReqBeanListRespVo.setVxAlipayReqBeanList(vxAlipayBillReqBeanVoList);
		return vxAlipayReqBeanListRespVo;

	}

}
